from nicegui import ui
from services.ocb.api import OcbApi
from services.ad936x.api import Ad936xApi
from datetime import datetime
from functools import partial

AD_API = Ad936xApi()
OCB_API = OcbApi()


def digital_tune(index: int):
    AD_API.digital_tune(index)

def digital_tune_all():
    AD_API.digital_tune_all()


with ui.row():
    with ui.card():
        link_0_current_label = ui.label('link 0 current: 0')
        link_1_current_label = ui.label('link 1 current: 0')
        service_0_current_label = ui.label('service 0 current: 0')
        service_1_current_label = ui.label('service 1 current: 0')
        service_2_current_label = ui.label('service 2 current: 0')
        service_3_current_label = ui.label('service 3 current: 0')
        service_5v_current_label = ui.label('service 5v current: 0')

    with ui.card():
        log = ui.log().style('width:55em')

    with ui.card():
        dt_buttons = [
            ui.button(text='DT AD 1', on_click=partial(digital_tune, 0)),
            ui.button(text='DT AD 2', on_click=partial(digital_tune, 1)),
            ui.button(text='DT AD 3', on_click=partial(digital_tune, 2)),
            ui.button(text='DT AD 4', on_click=partial(digital_tune, 3)),
            ui.button(text='DT AD ALL', on_click=digital_tune_all)
        ]

    with ui.card():
        def update():
            ocb_telemetry = OCB_API.get_all_ocb_current_28v()
            link_0_current_label.text = f'link 0 current: {ocb_telemetry.link_0_ocb:.3f}'
            link_1_current_label.text = f'link 0 current: {ocb_telemetry.link_1_ocb:.3f}'
            service_0_current_label.text = f'service 0 current: {ocb_telemetry.service_0_ocb:.3f}'
            service_1_current_label.text = f'service 1 current: {ocb_telemetry.service_1_ocb:.3f}'
            service_2_current_label.text = f'service 2 current: {ocb_telemetry.service_2_ocb:.3f}'
            service_3_current_label.text = f'service 3 current: {ocb_telemetry.service_3_ocb:.3f}'
            service_5v_current_label.text = f'service 5v current: {ocb_telemetry.service_5v_ocb:.3f}'

            time = datetime.now().strftime("%H:%M:%S")
            log.push(f'[{time}] -> l0: {ocb_telemetry.link_0_ocb:.2f}, l1: {ocb_telemetry.link_1_ocb:.2f}, s0: {ocb_telemetry.service_0_ocb:.2f}, s1: {ocb_telemetry.service_1_ocb:.2f}, s2: {ocb_telemetry.service_2_ocb:.2f}, s3: {ocb_telemetry.service_3_ocb:.2f}, sv5: {ocb_telemetry.service_5v_ocb:.2f}')

        update_button = ui.button('update', on_click=update)
        auto_update_timer = ui.timer(1.0, update, active=False)
        auto_update_switch = ui.switch('auto update').bind_value(auto_update_timer, 'active')


ui.run(port=8800, title='debug', reload=False, loop="asyncio")
